﻿using System.Linq;
using System.Reflection;
using System.Text;
using Nvigorate.Common;
using Nvigorate.Common.Reflection;
using Nvigorate.Data.Query;
using Nvigorate.Relational.Mapping.Interface;
using Nvigorate.Relational.Repository;

namespace Nvigorate.Relational.Builders
{
    public class DeleteBuilder
    {
        protected ISourceMap _map;
        protected IPersistable _persistable;

        protected Delete DeleteRecord
        {
            get
            {
                return new Delete(Table.From(_map.SourceName), Where.Criteria(WhereClause));
            }
        }

        protected CriteriaClause WhereClause
        {
            get
            {
                return new CriteriaClause(
                    _map.Assignments
                        .Where(a => a.PrimaryKey)
                        .Select(k => GetEqualCriterionFromAssignment(k).And()));
            }
        }

        protected Equal GetEqualCriterionFromAssignment(IAssignment assignment)
        {
            return Criterion.Column(assignment.Source.Field, assignment.Source.Entity)
                .EqualTo(new Literal(Reflector.Read(_persistable.Instance, assignment.Target.Field)));
        }

        public IQueryObject Build()
        {
            return DeleteRecord;
        }

        public DeleteBuilder(ISourceMap map, IPersistable persistable)
        {
            _map = map;
            _persistable = persistable;
        }
        
    }
}